package com.manulife.hk.performance.converter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.Optional;

@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<LocalDate, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDate localDate) {
    	Optional<LocalDate> date = Optional.ofNullable(localDate);
    	if(!date.isPresent()) {
    		return null;
    	}
        return Timestamp.valueOf(date.get().atStartOfDay());
    }
    @Override
    public LocalDate convertToEntityAttribute(Timestamp timestamp) {
    	Optional<Timestamp> stamp = Optional.ofNullable(timestamp);
    	if(!stamp.isPresent()) {
    		return null;
    	}
        return stamp.get().toLocalDateTime().toLocalDate();
    }
}
